import { useState, type RefObject, useImperativeHandle, } from "react";
import { Modal, Form, Input, Select, TreeSelect, message} from "antd";
import type { IDept, IUser } from "../../types/api.ts";
import api from "../../api/index.ts";


// props 里面有个ref属性，里面装着传递或者说暴露给父组件的方法或者属性等。因此interface是这么定义的。
interface IProps {
   ref: RefObject<{ showModal: (type:string, data?:IDept | {parentId: string}) => void; } | null>
   updataList:()=>void;
}

const CreateDept = ( props:IProps ) => {

  const [form] = Form.useForm();
  
  // 暴露给父组件的方法
  useImperativeHandle(props.ref,() => {
    return { 
        showModal,
     }
  })

  const [messageApi] = message.useMessage();

  const getDeptData = async () => {
      const res = await api.getDepartmentList();
      setDeptList(res);
    };

  const getAllUsers = async () => {
      const res = await api.getAllUserList();
      setUserList(res);
    };
  
  const [userList, setUserList] = useState<IUser[]>([])

  const [deptList,setDeptList] = useState<IDept[]>([])
  

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalType, setModalType] = useState<string>("")

  const showModal = (type:string, data?:IDept | { parentId:string }) => {
    console.log(props,135165)
    form.resetFields()
    setModalType(type)
    if(data) {
       form.setFieldsValue(data)
    }
    getDeptData()
    getAllUsers()
    setIsModalOpen(true);
  };

  const handleOk = async() => {
    // 接口肯定调不通
    const valid = await form.validateFields();
    if(!valid) return;

    if(modalType === "新建部门") {
        const res = await api.addDept(form.getFieldsValue())
        messageApi.success("添加成功"+res)
    }
    if(modalType === "编辑部门") {
        console.log(form.getFieldsValue())
        const res = await api.editDept(form.getFieldsValue())
        messageApi.success("编辑成功"+res)
    }
    // 父组件传递给子组件的方法，重新调一下父组件重新获取列表
    props.updataList()
    setIsModalOpen(false);
  };

  // 递归查找，找到对应的部门，然后添加子部门
  const pushData = ( data:IDept[], NewDeptName:string, NewDept:IDept ): boolean => {
     for(const item of data) {
        if(item.deptName === NewDeptName) {
           item.children.push(NewDept)
           return true
        }else if(item.children && item.children.length > 0) {
        const found = pushData(item.children,NewDeptName,NewDept )
           if (found) return true
        }
     }
     return false
  }

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const data: IDept[] = [
      {
        _id: "saidgasgdaysgda22aa3",
        createTime: "2023-11-22T08:23:39.919Z",
        updateTime: "2023-11-22T08:23:39.919Z",
        deptName: "开发部",
        userName: "张三",
        children: [
          {
            _id: "saidgasgdaysgda23",
            createTime: "2023-11-22T08:23:39.919Z",
            updateTime: "2025-11-22T08:23:39.919Z",
            deptName: "前端开发部",
            userName: "李四",
            parentId: 1,
            children: [],
          },
        ],
      },
      {
        _id: "saidgasgdaysgdas223",
        createTime: "2021-11-22T08:23:39.919Z",
        updateTime: "2023-11-22T08:23:39.919Z",
        deptName: "业务部",
        userName: "张三",
        children: [
          {
            _id: "saidgasgdaysgda22s3",
            createTime: "2023-11-22T08:23:39.919Z",
            updateTime: "2023-11-22T08:23:39.919Z",
            deptName: "大宗贸易部",
            userName: "李四",
            parentId: 1,
            children: [],
          },
        ],
      },
    ];
  const allUserData: IUser[] = [
    {
        _id: "saidgasgdaysgda223",
        userId: 1,
        userName: "王五",
        userEmail: "zhangsan@example.com",
        deptId: "saidgasgdaysgda223",
        state: 1,
        mobile: "1234567890",
        job: "前端开发工程师",
        role: 1,
        roleList: "admin,developer",
        deptName: "开发部",
        userImg:"/assets/images/avatar.png",
        createid:2,
    },
    {
        _id: "saidgasgdaysgda223s",
        userId: 1,
        userName: "诵律",
        userEmail: "zhangsan@example.com",
        deptId: "saidgasgdaysgda223s",
        state: 1,
        mobile: "1234567890",
        job: "前端开发工程师",
        role: 1,
        roleList: "admin,developer",
        deptName: "开发部",
        userImg:"/assets/images/avatar.png",
        createid:2,
    }
  ]


  return (
    <div>
      <Modal
        title={modalType}
        closable={{ "aria-label": "Custom Close Button" }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        width={500}
      >
        <Form className="search-form" form={form} labelCol={{ span: 6 }}>
          <Form.Item hidden name="_id" />
          <Form.Item
            label="上级部门"
            name="parentId"
            rules={[{ required: true, message: "请选择上级部门" }]}
          >
            <TreeSelect
              allowClear
              treeData={data}
              placeholder="请选择上级部门"
              treeDefaultExpandAll
              fieldNames={{ label: "deptName", value: "_id" }}
            />
          </Form.Item>
          <Form.Item
            label="部门名称"
            name="deptName"
            rules={[{ required: true, message: "请输入部门名称" }]}
          >
            <Input placeholder="请输入部门名称" />
          </Form.Item>
          <Form.Item
            label="负责人名称"
            name="userName"
            rules={[{ required: true, message: "请选择负责人" }]}
          >
            <Select>
              {allUserData.map((item) => (
                <Select.Option key={item._id} value={item.userName}>
                  {item.userName}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};
export default CreateDept;
